package com.lipeng.service.impl;

import com.lipeng.bean.Admin;
import com.lipeng.mapper.AdminMapper;
import com.lipeng.service.AdminService;
import com.lipeng.utils.AjaxResult;
import com.lipeng.utils.StrUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * Created by dllo on 18/3/1.
 */
@Service
public class AdminServiceImpl implements AdminService {

    @Resource
    private AdminMapper adminMapper;
    @Override
    public AjaxResult adminLogin(Admin admin) {
        AjaxResult result = new AjaxResult();
        Admin oldAdmin = new Admin();
        if (!loginArgs(admin)) {
            result.setCode("0");// 0代表注册失败
            result.setMessage("请输入合法的用户名和密码");
            return result;
        }
        if (userExist(admin.getName())) {
            oldAdmin = adminMapper.adminLogin(admin);
            if (oldAdmin == null){
                result.setCode("0");
                result.setMessage("密码错误");
                return result;
            }
        } else {
            result.setCode("0");
            result.setMessage("用户名不存在");
            return result;
        }
        Admin newAdmin = new Admin();
        newAdmin.setId(oldAdmin.getId());
        newAdmin.setName(oldAdmin.getName());
        result.setCode("1");
        result.setMessage("登陆成功");
        result.setData(newAdmin);
        return result;
    }

    //判断账户是否存在
    @Override
    public boolean userExist(String username) {
        return adminMapper.userExist(username) > 0;
    }

    private boolean loginArgs(Admin admin) {
        // 用户名和密码不能为空
        if (StrUtils.isNull(admin.getName()) ||
                StrUtils.isNull(admin.getPsw())) {
            return false;
        }
        return true;
    }
    // 判断参数是否合法
    private boolean userArgs(Admin admin) {

        // 用户名和密码不能为空
        if (StrUtils.isNull(admin.getName()) ||
                StrUtils.isNull(admin.getPsw())) {
            return false;
        }


        return true;

        // 97~102行也可以如下替换
//        return StrUtils.isPhoneNumberRight(user.getTel());
    }
}
